package com.hunantv.mglive.ui.discovery;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.handmark.pulltorefresh.librarymgtv.PullToRefreshBase;
import com.handmark.pulltorefresh.librarymgtv.PullToRefreshListView;
import com.hunantv.mglive.R;
import com.hunantv.mglive.common.BuildConfig;
import com.hunantv.mglive.common.DiscoveryConstants;
import com.hunantv.mglive.common.FormEncodingBuilderEx;
import com.hunantv.mglive.common.MaxApplication;
import com.hunantv.mglive.common.OnTouchImpl;
import com.hunantv.mglive.data.ResultModel;
import com.hunantv.mglive.data.StarModel;
import com.hunantv.mglive.data.discovery.DynamicCommen;
import com.hunantv.mglive.data.discovery.DynamicData;
import com.hunantv.mglive.ui.discovery.dynamic.CommentList;
import com.hunantv.mglive.ui.discovery.dynamic.PictureView;
import com.hunantv.mglive.utils.GlideRoundTransform;
import com.hunantv.mglive.utils.HttpUtils;
import com.hunantv.mglive.utils.MGTVUtil;
import com.hunantv.mglive.utils.SharePreferenceUtils;
import com.hunantv.mglive.utils.StringUtil;
import com.hunantv.mglive.utils.Toast;
import com.hunantv.mglive.widget.loadingView.LoadingViewHelper;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 动态列表页面
 * <p/>
 * Created by June Kwok on 2015/11/14.
 */
public class DynamicLayout extends FrameLayout implements HttpUtils.callBack,View.OnClickListener,AdapterView.OnItemClickListener {

    private static final int KEY_LIST_DYNAMIC_ITEM = R.layout.item_dynamic_list;

    private DynamicListAdapter mAdapter;
    private DynamicList mDynamicList;

    private EditBtnView mEdtFrame;
    private LoadingViewHelper mLoadingViewHelper;

    private int STAR_PAGE_INDEX = 1;
    private int mPageIndex = STAR_PAGE_INDEX, mPagerSize = 20;
    private boolean mIsRefresh = false;//加载数据

    private List<DynamicData> mList;
    private DynamicData mCurrentDynamicData;

    private HttpUtils mHttp;
    private Context mContext;
    private SharePreferenceUtils sharePreferenceUtils;

    /**
     * true:广场模式
     * false:艺人空间模式
     */
    private boolean isSquareModle = true;
    public void setIsSquareModle(boolean isSquareModle) {
        this.isSquareModle = isSquareModle;
    }
    /**
     * 如果是艺人空间模式 需要传艺人信息
     */
    private StarModel mStarInfo;
    public StarModel getStarInfo() {
        return mStarInfo;
    }
    public void setStarInfo(StarModel mStarInfo) {
        this.mStarInfo = mStarInfo;
    }

    public DynamicList getDynamicList() {
        return mDynamicList;
    }

    public void setDynamicList(DynamicList mDynamicList) {
        this.mDynamicList = mDynamicList;
    }

    public int getPageIndex() {
        return mPageIndex;
    }

    public boolean isFirstPage() {
        return mPageIndex == STAR_PAGE_INDEX;
    }


    public DynamicLayout(Context context,AttributeSet attributeSet){
        super(context,attributeSet);
        mContext = context;
        sharePreferenceUtils = new SharePreferenceUtils(getContext(), SharePreferenceUtils.FILE_KEY_ZAN_DATA);

        resetData();
        initView();
        initReceiver();
    }

    /**
     * 加载数据
     */
    public void loadData() {
        if (null == mList) {
            mList = new ArrayList<>();
        }
        if (mList.size() == 0) {
            mLoadingViewHelper.showLoading();
        }

        getUpdatedList(true);
    }

    /**
     * 初始化动态列表
     */
    private void initView() {
        setDynamicList(new DynamicList(getContext()));
        getDynamicList().setMode(PullToRefreshBase.Mode.BOTH);
        getDynamicList().setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                getUpdatedList(true);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                getMoreList(true);
            }
        });
        LayoutParams mDynamicListLP = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        getDynamicList().setLayoutParams(mDynamicListLP);
        getDynamicList().getRefreshableView().setDividerHeight(0);
        addView(getDynamicList());

        FrameLayout.LayoutParams mEdtFrameLP = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, (int)(45*getContext().getResources().getDisplayMetrics().density));
        mEdtFrameLP.gravity = Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM;
        mEdtFrame = new EditBtnView(getContext());
        mEdtFrame.setLayoutParams(mEdtFrameLP);
        mEdtFrame.setVisibility(GONE);
        addView(mEdtFrame);
        mEdtFrame.mTxtSend.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (StringUtil.isNullorEmpty(mEdtFrame.mEditText.getText().toString())) {
                    return;
                }
                addCommen(BuildConfig.URL_DYNAMIC_ADD_COMMEN, mCurrentDynamicData, mEdtFrame.mEditText.getText().toString());
                mEdtFrame.mEditText.setText("");
                InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(mEdtFrame.mEditText.getWindowToken(), 0);
                mEdtFrame.setVisibility(GONE);
            }
        });

        mLoadingViewHelper = new LoadingViewHelper(this.mDynamicList);
    }

    /**
     * 获取更多动态列表
     *
     * @param isRefresh
     */
    private void getMoreList(boolean isRefresh) {
        if (isRefresh) {
            getDynamicList().setRefreshing();
            mPageIndex++;
            requestDate(mPageIndex, mPagerSize);
        }
        mIsRefresh = isRefresh;
    }

    /**
     * 获取最新的动态列表
     *
     * @param isRefresh
     */
    private void getUpdatedList(boolean isRefresh) {
        if (isRefresh) {
            getDynamicList().setRefreshing();
        }
        mPageIndex = STAR_PAGE_INDEX;
        requestDate(STAR_PAGE_INDEX, mPagerSize);
        mIsRefresh = isRefresh;
    }

    /**
     * Post请求数据
     *
     * @param pageNum  页数
     * @param pageSize
     */
    private void request(int pageNum, int pageSize) {
        Map<String, String> param = new FormEncodingBuilderEx().add("uid", MaxApplication.getInstance().getUid())
                .add("page", pageNum + "")
                .add("token", MaxApplication.getInstance().getToken())
                .add("type", "0").add("dyType", "1")
                .add("pageSize", pageSize + "").build();
        post(BuildConfig.URL_MY_DYNAMIC, param);
    }

    /**
     * Post请求数据
     *
     * @param pageNum  页数
     * @param pageSize
     */
    private void requestDate(int pageNum, int pageSize) {
        if (isSquareModle)
            request(pageNum, pageSize);
        else {
            requestStarDynamic(pageNum, pageSize);
        }
    }

    /**
     * 获取艺人的空间动态
     */
    private void requestStarDynamic(int pageNum, int pageSize) {
        if (null == getStarInfo()) {
            return;
        }
        Map<String, String> param = new FormEncodingBuilderEx().add("uid", MaxApplication.getInstance().getUid()).add("page", pageNum + "").add("pageSize", pageSize + "")
                .add("artistId", getStarInfo().getUid())
                .add("uId", MaxApplication.getInstance().getToken())
                .add("dyType", "1")
                .add("token", MaxApplication.getInstance().getToken())
                .build();
        post(BuildConfig.URL_STAR_DYNAMIC, param);
    }

    @Override
    public boolean get(String url, Map<String, String> param) {
        return false;
    }


    /**
     * POST 方法
     *
     * @param url
     * @param param 参数
     * @return
     */
    public boolean post(String url, Map<String, String> param) {
        if(mHttp == null){
            mHttp = new HttpUtils(mContext,this);
        }
        return mHttp.post(url, param);
    }

    /**
     * 注册删除动态的广播
     */
    BroadcastReceiver mReceiver;

    /**
     * 注册广播监听动态改动
     */
    private void initReceiver() {
        if (mReceiver != null) {
            return;
        }
        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction(DiscoveryConstants.ACTION_DEL_DYNAMIC);
        mFilter.addAction(DiscoveryConstants.ACTION_UPDATE_DYNAMIC);
        mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (DiscoveryConstants.ACTION_DEL_DYNAMIC.equals(action)) {
                    String dynamicId = intent.getStringExtra(DiscoveryConstants.KEY_DEL_DYNAMIC);
                    if (!StringUtil.isNullorEmpty(dynamicId)) {
                        updateDynamicList();
                    }
                } else if (DiscoveryConstants.ACTION_UPDATE_DYNAMIC.equals(action)) {
                    updateDynamicList();
                }
            }
        };
        getContext().registerReceiver(mReceiver, mFilter);
    }

    public void onDestroy() {
        if (null != mReceiver) {
            getContext().unregisterReceiver(mReceiver);
            mReceiver = null;
        }
    }

    /**
     * 更新列表的数据
     */
    public void updateDynamicList() {
        getUpdatedList(false);
    }

    /**
     * 清除数据
     */
    public void resetData() {
        clearData();
        if (isSquareModle) {
            STAR_PAGE_INDEX = 1;
            mPageIndex = STAR_PAGE_INDEX;
            mPagerSize = 20;
        } else {
            STAR_PAGE_INDEX = 1;
            mPageIndex = STAR_PAGE_INDEX;
            mPagerSize = 20;
        }
    }

    /**
     * 清除数据
     */
    public void clearData() {
        if (null != this.mList) {
            this.mList.clear();
        }
    }

    /**
     * 动态列表数据是否为空
     */
    public boolean isEmptyData(){
        if (null != this.mList && this.mList.size()>0) {
            return false;
        }

        return true;
    }

    /**
     * 更新加载之后的数据显示
     */
    private void updateView(List<DynamicData> mList) {
        this.mList.addAll(mList);
        if (null != mAdapter) {
            mAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 更新评论列表
     */
    public void updateCommen() {
        if (null != mAdapter) {
            mAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 添加评论
     *
     */
    private void addCommen(String url, DynamicData dynamicData, String content) {
        if(dynamicData ==null){
            return;
        }
        Map<String, String> param = new FormEncodingBuilderEx().add("dynamicId", dynamicData.getDynamicId() + "").add("token", MaxApplication.getInstance().getToken()).add("uid", MaxApplication.getInstance().getUid()).add("content", content).build();
        post(url, param);
        long count = dynamicData.getCommentCount();
        count++;
        dynamicData.setCommentCount(count);
        dynamicData.getNewCommen(MaxApplication.getInstance().getUid(), MaxApplication.getInstance().getUserInfo().getNickName(), content);
        updateCommen();
    }

    /**
     * 添加赞
     *
     * @param url
     * @param dynamicId
     */
    private void addPraise(String url, String dynamicId) {
        Map<String, String> param = new FormEncodingBuilderEx().add("dynamicId", dynamicId + "").add("token", MaxApplication.getInstance().getUserInfo().getToken()).add("uid", MaxApplication.getInstance().getUid()).build();
        post(url, param);
    }

    /**
     * 删除赞
     *
     * @param url
     * @param dynamicId
     */
    private void removePraise(String url, String dynamicId) {
        Map<String, String> param = new FormEncodingBuilderEx().add("dynamicId", dynamicId + "").add("token", MaxApplication.getInstance().getUserInfo().getToken()).add("uid", MaxApplication.getInstance().getUid()).build();
        post(url, param);
    }


    public void onFailure(String url, ResultModel resultModel) {
        getDynamicList().onRefreshComplete();
        mPageIndex--;
        if(mPageIndex<1){
            mPageIndex = 1;
        }
        if ((mList.size() == 0) && (url.contains(BuildConfig.URL_MY_DYNAMIC) || url.contains(BuildConfig.URL_STAR_DYNAMIC))) {
            showErrorView();
        } else {
            Toast.makeText(getContext(), "啊哦，服务器开小差了，刷新试试吧～", Toast.LENGTH_SHORT).show();
        }
    }

    public void onError(String url, Exception e) {
        getDynamicList().onRefreshComplete();
        mPageIndex--;
        if(mPageIndex<1){
            mPageIndex = 1;
        }

        if ((mList.size() == 0) && (url.contains(BuildConfig.URL_MY_DYNAMIC) || url.contains(BuildConfig.URL_STAR_DYNAMIC))) {
            showErrorView();
        } else {
            Toast.makeText(getContext(), "啊哦，服务器开小差了，刷新试试吧～", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public Object asyncExecute(String url, ResultModel resultModel) {
        return null;
    }

    /**
     * 显示加载失败视图
     */
    private void showErrorView() {
        if (mLoadingViewHelper != null) {
            mLoadingViewHelper.showError(R.string.refresh, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    loadData();
                }
            });
        }
    }

    public void onSucceed(String url, ResultModel resultModel) {

        if (url.contains(BuildConfig.URL_MY_DYNAMIC) || url.contains(BuildConfig.URL_STAR_DYNAMIC)) {

            getDynamicList().onRefreshComplete();

            try {
                List<DynamicData> arrray = JSON.parseArray(resultModel.getData(), DynamicData.class);

                //处理接口结果数据
                if (null != arrray && arrray.size() > 0) {
                    if (null == mList) {
                        mList = new ArrayList<>();
                    }
                    if (mPageIndex == STAR_PAGE_INDEX) {
                        clearData();
                    }

                    if(arrray.size()<mPagerSize){//一页不满，取消上拉加载更多
                        getDynamicList().setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                    }else{
                        getDynamicList().setMode(PullToRefreshBase.Mode.BOTH);
                    }
                    updateView(arrray);
                    Log.i("JUNE", "mList=" + mList.size());
                    if (mLoadingViewHelper != null) {
                        mLoadingViewHelper.restore();
                    }
                } else {

                    mPageIndex--;
                    if(mPageIndex<1){
                        mPageIndex = 1;
                    }

                    //空数据
                    if (mList == null || mList.size() == 0) {
                        if (isSquareModle) {
                            mLoadingViewHelper.showEmpty(R.string.empty_dynamic, R.drawable.empty_dynamic);
                        } else {
                            mLoadingViewHelper.showEmpty(R.string.empty_live_dynamic, R.drawable.empty_live_dynamic);
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (BuildConfig.URL_DYNAMIC_DEL_PRAISE.equals(url)) {
            Map<String, String> param = resultModel.getParam();
            String dynamicId = param.get("dynamicId");
            SharePreferenceUtils sharePreferenceUtils = new SharePreferenceUtils(getContext(), SharePreferenceUtils.FILE_KEY_ZAN_DATA);
            sharePreferenceUtils.removeZanDynamic(dynamicId);
        } else if (BuildConfig.URL_DYNAMIC_ADD_PRAISE.equals(url)) {
            Map<String, String> param = resultModel.getParam();
            String dynamicId = param.get("dynamicId");
            SharePreferenceUtils sharePreferenceUtils = new SharePreferenceUtils(getContext(), SharePreferenceUtils.FILE_KEY_ZAN_DATA);
            sharePreferenceUtils.addZanDynamic(dynamicId);
        }
    }

    /**
     * 跳转到动态详情
     *
     * @param data
     */
    public void JumpToDetail(Object data) {
        if (null == data || !(data instanceof DynamicData)) {
            return;
        }
        Intent mIntent = new Intent(getContext(), DetailsActivity.class);
        mIntent.putExtra("dynamicdata", (DynamicData) data);
        ((Activity) getContext()).startActivity(mIntent);
    }


    /**
     * 跳转到登陆页面
     */
    public void jumpToLogin(String title) {
        MGTVUtil.getInstance().login(MaxApplication.getAppContext());
    }

    @Override
    public void onClick(View v) {
        int position = (Integer)v.getTag(KEY_LIST_DYNAMIC_ITEM);
        int id = v.getId();
        DynamicData mData = mList.get(position);
        if(mData != null){
            if(id == R.id.item_dynamic_list){//详情
                JumpToDetail(mData);
            }else if(id == R.id.dynamic_list_comment_list_input_edit || id == R.id.comment_action){//评论
                showImm(mData,null);
            }else if(id == R.id.zan_action) {//赞，取消赞
                doPraise(mData,v);
            }
        }


    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        int parentPosi = (Integer)parent.getTag(KEY_LIST_DYNAMIC_ITEM);
        int idParent = parent.getId();
        if(idParent == R.id.dynamic_list_comment_list){//@某人
            DynamicData dynamicData = mList.get(parentPosi);
            List<DynamicCommen> mComList = dynamicData.getComments();
            String str = "";
            Object obj = mComList.get(position);
            if (null != obj && obj instanceof DynamicCommen) {
                str = ((DynamicCommen) obj).getNickName();
            }
            showImm(dynamicData,str);
        }

    }

    /**
     * 处理赞，取消赞事件
     * @param mData
     * @param v
     */
    private void doPraise(DynamicData mData,View v){
        if (!MaxApplication.getInstance().isLogin()) {
            jumpToLogin("登录以后才可以点赞哦~");
            return;
        }
        TextView textView = (TextView)v.findViewById(R.id.zan_action_num);
        ImageView imageView = (ImageView)v.findViewById(R.id.zan_action_image);
        long n = mData.getPraiseCount();
        String idStr = mData.getDynamicId();
        boolean bol = mData.isPraised();
        if (!bol) {
            n++;
            if (n < 0) {
                n = 0;
            }
            addPraise(BuildConfig.URL_DYNAMIC_ADD_PRAISE, idStr);

            if (n > 0) {
                textView.setText("" + n);
            } else {
                textView.setText(getContext().getString(R.string.praise));
            }
            imageView.setImageResource(R.drawable.max_dynamic_praise_on);

            mData.setPraiseCount(n);
            mData.setIsPraised(true);
            sharePreferenceUtils.addZanDynamic(mData.getDynamicId());

        } else {
            n--;
            if (n < 0) {
                n = 0;
            }

            removePraise(BuildConfig.URL_DYNAMIC_DEL_PRAISE, idStr);

            if (n > 0) {
                textView.setText("" + n);
            } else {
                textView.setText(getContext().getString(R.string.praise));
            }
            imageView.setImageResource(R.drawable.max_dynamic_praise_off);
            mData.setPraiseCount(n);
            mData.setIsPraised(false);
            sharePreferenceUtils.removeZanDynamic(mData.getDynamicId());
        }
    }

    /**
     * 弹出编辑弹窗
     * @param txt
     */
    private void showImm(DynamicData mData , String txt) {
        if (!MaxApplication.getInstance().isLogin()) {
            jumpToLogin("登录以后才可以评论哦~");
            return;
        }
        mCurrentDynamicData = mData;
        mEdtFrame.setVisibility(VISIBLE);
        mEdtFrame.mEditText.requestFocus();
        mEdtFrame.mEditText.requestFocusFromTouch();
        if (!StringUtil.isNullorEmpty(txt)) {
            mEdtFrame.mEditText.setText("@" + txt + " ");
            mEdtFrame.mEditText.setSelection(mEdtFrame.mEditText.getText().length());
        }
        //打开软键盘
        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(mEdtFrame.mEditText, InputMethodManager.SHOW_FORCED);
    }

    /**
     * 动态页面的适配器
     */
    private class DynamicListAdapter extends BaseAdapter {

        List<DynamicData> mDataList;

        public DynamicListAdapter(List<DynamicData> mDataList) {
            setDataList(mDataList);
        }

        @Override
        public int getCount() {
            if (null != getDataList()) {
                return getDataList().size();
            }
            return 0;
        }

        @Override
        public Object getItem(int position) {
            if (null != getDataList()) {
                return getDataList().get(position);
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public int getViewTypeCount() {
            return 3;
        }

        @Override
        public int getItemViewType(int position) {
            DynamicData mData = getDataList().get(position);
            int type = mData.getType();
            if (type == 3 || type == 2) {//直播
                return 2;
            }else if(type == 1){
                return 1;
            }else{
                return 0;
            }
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            DynamicListViewHolder dynamicListViewHolder;
            int itemType = getItemViewType(position);
            if(convertView == null || convertView.getTag() == null
                    || ((Integer)convertView.getTag(R.id.dynamic_list_tag)) != itemType){
                convertView = LayoutInflater.from(mContext).inflate(R.layout.item_dynamic_list,null);
                dynamicListViewHolder = new DynamicListViewHolder();
                dynamicListViewHolder.assignViews(convertView);
                if(itemType == 1)
                {
                    dynamicListViewHolder.mDynamicDetailVedioView.setVisibility(View.VISIBLE);
                    dynamicListViewHolder.mDynamicDetailImageView.setVisibility(View.GONE);
                }else if(itemType == 2){
                    dynamicListViewHolder.mDynamicDetailVedioView.setVisibility(View.VISIBLE);
                    dynamicListViewHolder.mDynamicDetailImageView.setVisibility(View.GONE);

                }else if(itemType == 0){
                    dynamicListViewHolder.mDynamicDetailVedioView.setVisibility(View.GONE);
                    dynamicListViewHolder.mDynamicDetailImageView.setVisibility(View.GONE);
                }
                convertView.setTag(dynamicListViewHolder);
            }else{
                dynamicListViewHolder = (DynamicListViewHolder)convertView.getTag();
            }
            convertView.setTag(R.id.dynamic_list_tag,itemType);
            //设置点击监听
            dynamicListViewHolder.setListener(position);

            if (getDataList() != null && getDataList().get(position) != null) {
                    DynamicData mData = getDataList().get(position);
                    String name = mData.getNickName();
                    String time = mData.getDate();
                    String photo = mData.getPhoto();
                    String desc = mData.getContent();
                    String imageUrl = photo;

                    long count = mData.getPraiseCount();
                    long commentCount = mData.getCommentCount();
                    boolean isPraised = sharePreferenceUtils.isZaned(mData.getDynamicId());
                    mData.setIsPraised(isPraised);

                    int type = mData.getType();
                    if (type == 3) {//直播
                        //TODO test
                        imageUrl = mData.getCover();
                        if (StringUtil.isNullorEmpty(imageUrl)) {
                            imageUrl = mData.getPhoto();
                        }
                        dynamicListViewHolder.mDynamicDetailVedioView.setVisibility(View.VISIBLE);
                        dynamicListViewHolder.mDynamicDetailImageView.setVisibility(View.GONE);

                        Glide.with(getContext()).load(imageUrl).placeholder(R.drawable.default__img_11).error(R.drawable.default__img_11).into(dynamicListViewHolder.mDynamicListVedioBg);

                    } else if (type == 2) {//视频
                        String cover = mData.getVideo().getCover();
                        if (!StringUtil.isNullorEmpty(cover)) {
                            imageUrl = cover;
                        }
                        dynamicListViewHolder.mDynamicDetailVedioView.setVisibility(View.VISIBLE);
                        dynamicListViewHolder.mDynamicDetailImageView.setVisibility(View.GONE);

                        Glide.with(getContext()).load(imageUrl).placeholder(R.drawable.default__img_11).error(R.drawable.default__img_11).into(dynamicListViewHolder.mDynamicListVedioBg);

                    } else if (type == 1) {//图片

                        if (mData.getImages() != null) {
                            dynamicListViewHolder.mDynamicDetailImageView.notifyChanged(mData.getImages());
                        }

                        dynamicListViewHolder.mDynamicDetailVedioView.setVisibility(View.GONE);
                        dynamicListViewHolder.mDynamicDetailImageView.setVisibility(View.VISIBLE);
                    }else{
                        dynamicListViewHolder.mDynamicDetailVedioView.setVisibility(View.GONE);
                        dynamicListViewHolder.mDynamicDetailImageView.setVisibility(View.GONE);
                    }

                    //填充数据
                    dynamicListViewHolder.mDynamicdListTitleRe.setVisibility(View.VISIBLE);
                    dynamicListViewHolder.mDynamicListActionLay.setVisibility(View.VISIBLE);
                    dynamicListViewHolder.mDynamicListCommentLay.setVisibility(View.VISIBLE);

                    if (!StringUtil.isNullorEmpty(name)) {
                        dynamicListViewHolder.mTvDynamicListName.setText(name);
                    } else {
                        dynamicListViewHolder.mTvDynamicListName.setText("");
                    }
                    if (!StringUtil.isNullorEmpty(desc)) {
                        dynamicListViewHolder.mTvDynamicListContent.setText(desc);
                    } else {
                        dynamicListViewHolder.mTvDynamicListContent.setText("");
                    }
                    if (!StringUtil.isNullorEmpty(time)) {
                        dynamicListViewHolder.mTimeText.setText(time);
                    } else {
                        dynamicListViewHolder.mTimeText.setText("");
                    }
                    if (!StringUtil.isNullorEmpty(photo)) {
                        dynamicListViewHolder.mIvDynamicListHead.setVisibility(View.VISIBLE);
                        Glide.with(getContext()).load(photo).error(R.drawable.default_icon).placeholder(R.drawable.default_icon)
                                .transform(new GlideRoundTransform(getContext(), R.dimen.height_32dp)).into(dynamicListViewHolder.mIvDynamicListHead);
                    } else {
                        dynamicListViewHolder.mIvDynamicListHead.setImageBitmap(null);
                    }

                    if (count > 0) {
                        dynamicListViewHolder.mZanActionNum.setText("" + count);
                    } else {
                        dynamicListViewHolder.mZanActionNum.setText(getContext().getString(R.string.praise));
                    }

                    if (commentCount > 0) {
                        dynamicListViewHolder.mCommentActionNum.setText("" + commentCount);
                    } else {
                        dynamicListViewHolder.mCommentActionNum.setText(getContext().getString(R.string.comment));
                    }

                    if (isPraised) {
                        dynamicListViewHolder.mZanActionImage.setImageResource(R.drawable.max_dynamic_praise_on);
                    } else {
                        dynamicListViewHolder.mZanActionImage.setImageResource(R.drawable.max_dynamic_praise_off);
                    }

                    //评论
                    dynamicListViewHolder.mDynamicListCommentListInputMore.setVisibility(View.GONE);
                    if (null != mData.getComments()) {
                        List<Object> comments = mData.getObjectCommentsList();
                        if(comments.size()>5){//控制长度
                            comments = comments.subList(0,5);
                        }
                        dynamicListViewHolder.mDynamicListCommentList.notifyChanged(comments);
                        if(mData.getCommentCount()>5){
                            dynamicListViewHolder.mDynamicListCommentListInputMore.setVisibility(View.VISIBLE);
                        }
                    } else {
                        dynamicListViewHolder.mDynamicListCommentList.notifyChanged(new ArrayList<Object>());
                    }
                    dynamicListViewHolder.mDynamicListCommentList.setOnItemClickListener(DynamicLayout.this);

                    //最后一行取消分割线
                    if(position == getCount()-1){
                        dynamicListViewHolder.mDiliverView.setVisibility(View.GONE);

                    }else{
                        dynamicListViewHolder.mDiliverView.setVisibility(View.VISIBLE);
                    }

                } else {//清空数据
                    dynamicListViewHolder.mDynamicdListTitleRe.setVisibility(View.GONE);
                    dynamicListViewHolder.mDynamicListActionLay.setVisibility(View.GONE);
                    dynamicListViewHolder.mDynamicListCommentLay.setVisibility(View.GONE);
                    dynamicListViewHolder.mDiliverView.setVisibility(View.GONE);
                }

            return convertView;
        }

        public List<DynamicData> getDataList() {
            return mDataList;
        }

        public void setDataList(List<DynamicData> mDataList) {
            this.mDataList = mDataList;
        }
    }

    /**
     * 动态页ListView
     */
    public class DynamicList extends PullToRefreshListView {
        OnTouchImpl onTouch;

        @Override
        public boolean dispatchTouchEvent(MotionEvent ev) {
            onTouch.onTouch(null, ev);
            return super.dispatchTouchEvent(ev);
        }

        public DynamicList(Context context) {
            super(context);
            init();
            onTouch = new OnTouchImpl(getContext()) {
                @Override
                public boolean onDown(MotionEvent e) {
                    if (mEdtFrame.getVisibility() == VISIBLE) {
                        mEdtFrame.mEditText.setText("");
                        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.hideSoftInputFromWindow(mEdtFrame.mEditText.getWindowToken(), 0);
                        mEdtFrame.setVisibility(GONE);
                        return false;
                    }
                    return super.onDown(e);
                }
            };
        }

        private void init() {
            if (null == mList) {
                mList = new ArrayList<>();
            }
            mAdapter = new DynamicListAdapter(mList);
            setAdapter(mAdapter);
            setVerticalScrollBarEnabled(false);
            //setDivider(null);
            setDividerPadding(0);

        }
    }

    /**
     * 动态列表itemViewHolder
     */
    public class DynamicListViewHolder{

         View mRootView;
         RelativeLayout mDynamicdListTitleRe;
         ImageView mIvDynamicListHead;
         TextView mTvDynamicListName;
         TextView mTvDynamicListContent;
         PictureView mDynamicDetailImageView;
         View mDynamicDetailVedioView;
         ImageView mDynamicListVedioBg;
         RelativeLayout mDynamicListActionLay;
         TextView mTimeText;
         LinearLayout mZanAction;
         ImageView mZanActionImage;
         TextView mZanActionNum;
         LinearLayout mCommentAction;
         ImageView mCommentActionImage;
         TextView mCommentActionNum;
         RelativeLayout mDynamicListCommentLay;
         CommentList mDynamicListCommentList;
         RelativeLayout mDynamicListCommentListInputRe;
         RelativeLayout mDynamicListCommentListInputMore;
         ImageView mDynamicListCommentListMoreIcon;
         RelativeLayout mDynamicListCommentListInputEdit;
         View mDiliverView;

        private void assignViews(View rootView) {
            mRootView = rootView;
            mDynamicdListTitleRe = (RelativeLayout) rootView.findViewById(R.id.dynamicd_list_title_re);
            mIvDynamicListHead = (ImageView) rootView.findViewById(R.id.iv_dynamic_list_head);
            mTvDynamicListName = (TextView) rootView.findViewById(R.id.tv_dynamic_list_name);
            mTvDynamicListContent = (TextView) rootView.findViewById(R.id.tv_dynamic_list_content);
            mDynamicDetailImageView = (PictureView)rootView.findViewById(R.id.dynamic_list_image_view);
            mDynamicDetailVedioView = rootView.findViewById(R.id.dynamic_list_vedio_view);
            mDynamicListVedioBg = (ImageView)rootView.findViewById(R.id.iv_dynamic_list_bg);
            mDynamicListActionLay = (RelativeLayout) rootView.findViewById(R.id.dynamic_list_action_lay);
            mTimeText = (TextView) rootView.findViewById(R.id.time_text);
            mZanAction = (LinearLayout) rootView.findViewById(R.id.zan_action);
            mZanActionImage = (ImageView) rootView.findViewById(R.id.zan_action_image);
            mZanActionNum = (TextView) rootView.findViewById(R.id.zan_action_num);
            mCommentAction = (LinearLayout) rootView.findViewById(R.id.comment_action);
            mCommentActionImage = (ImageView) rootView.findViewById(R.id.comment_action_image);
            mCommentActionNum = (TextView) rootView.findViewById(R.id.comment_action_num);
            mDynamicListCommentLay = (RelativeLayout) rootView.findViewById(R.id.dynamic_list_comment_lay);
            mDynamicListCommentList = (CommentList) rootView.findViewById(R.id.dynamic_list_comment_list);
            mDynamicListCommentListInputRe = (RelativeLayout) rootView.findViewById(R.id.dynamic_list_comment_list_input_re);
            mDynamicListCommentListInputMore = (RelativeLayout) rootView.findViewById(R.id.dynamic_list_comment_list_input_more);
            mDynamicListCommentListMoreIcon = (ImageView) rootView.findViewById(R.id.dynamic_list_comment_list_more_icon);
            mDynamicListCommentListInputEdit = (RelativeLayout) rootView.findViewById(R.id.dynamic_list_comment_list_input_edit);
            mDiliverView = rootView.findViewById(R.id.diliver_line);
        }

        private void setListener(int position){
            mRootView.setTag(KEY_LIST_DYNAMIC_ITEM,position);
            mDynamicListCommentListInputEdit.setTag(KEY_LIST_DYNAMIC_ITEM,position);
            mZanAction.setTag(KEY_LIST_DYNAMIC_ITEM,position);
            mCommentAction.setTag(KEY_LIST_DYNAMIC_ITEM,position);
            mDynamicListCommentList.setTag(KEY_LIST_DYNAMIC_ITEM,position);

            mRootView.setOnClickListener(DynamicLayout.this);
            mDynamicListCommentListInputEdit.setOnClickListener(DynamicLayout.this);
            mZanAction.setOnClickListener(DynamicLayout.this);
            mCommentAction.setOnClickListener(DynamicLayout.this);
            mDynamicListCommentList.setOnItemClickListener(DynamicLayout.this);

        }

    }



}
